package cn.vivi.tag.service.impl;

import cn.vivi.common.entity.BlogTag;
import cn.vivi.common.entity.Tag;
import cn.vivi.tag.mapper.BlogTagMapper;
import cn.vivi.tag.mapper.TagMapper;
import cn.vivi.tag.service.BlogTagService;
import cn.vivi.tag.service.TagService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private BlogTagMapper blogTagMapper;

    @Autowired
    private BlogTagService blogTagService;

    @Override
    public Tag findById(String id) {
        return tagMapper.selectById(id);
    }

    @Override
    public List<Tag> findByBlogId(String id) {
        QueryWrapper<BlogTag> wrapper = new QueryWrapper<>();
        wrapper.eq("blog_id", id);
        List<BlogTag> blogTags = blogTagMapper.selectList(wrapper);
        if (blogTags.size() == 0) {
            return Collections.emptyList();
        }
        ArrayList<String> tagIds = new ArrayList<>(16);
        blogTags.forEach(blogTag -> {
            tagIds.add(blogTag.getTagId());
        });
        return tagMapper.selectBatchIds(tagIds);
    }

    @Override
    public Page<Tag> findByPage(long current, long size) {
        return tagMapper.selectPage(new Page<>(current, size), null);
    }

    @Override
    public boolean updateTag(Tag tag) {
        return tagMapper.updateById(tag) > 0;
    }

    @Override
    public boolean deleteTag(String id) {
        int result = tagMapper.deleteById(id);
        return result > 0 && blogTagService.deleteByTagId(id);
    }

    @Override
    public boolean addTag(Tag tag) {
        return tagMapper.insert(tag) > 0;
    }

}
